/*
 * This file is subject to the terms and conditions of the GNU General Public
 * License. See the file "COPYING" in the main directory of this archive for
 * more details.
 *
 * Copyright (C) 2008, 2009 Antonio Vieiro, all rights reserved.
 *
 */
package org.schemeway.plugins.schemescript.editor;

import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.runtime.*;
import org.schemeway.plugins.schemescript.*;

import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.btree.BTree;
import jdbm.helper.StringComparator;


/**
 * R5RSCompletionDatabase is a singleton class that keeps a reference
 * to a JDBM database, and allows querying for completion info to that
 * database.
 * @author Antonio Vieiro (antonio@antonioshome.net)
 */
public class R5RSCompletionDatabase
{

  private static R5RSCompletionDatabase instance = new R5RSCompletionDatabase();

  public static R5RSCompletionDatabase getInstance()
  {
    return instance;
  }
  private RecordManager recordManager;
  private BTree index;
  private TreeSet<String> keywords;

  @SuppressWarnings("unchecked")
  
  public Collection<String> lookup(String prefix, int firstOffset, int lastOffset)
  {
    getDatabase();
    if (recordManager == null)
    {
      Logger.getLogger(getClass().getName()).severe("Error getting database!");
      return Collections.EMPTY_LIST;
    }

    SortedSet<String> possibleKeywords = keywords.tailSet(prefix);

    ArrayList<String> items = new ArrayList<String>();

    for (String k : possibleKeywords)
    {
      if (k.startsWith(prefix))
      {
        try
        {
          items.add(getItem(k));
        }
        catch (Exception e)
        {
          Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error getting keyword '" +
            k + "' from R5RS Completion database");
        }
      }
    }
    return items;
  }

  public String getItem(String keyword)
  {
	getDatabase();
	try {
    String keywordType = (String) index.find(keyword + ".type");
    String keywordSyntax = (String) index.find(keyword + ".syntax");
    String keywordDoc = (String) index.find(keyword + ".doc");
      return keywordDoc;
	}catch(Exception e)
	{
      return null;
	}
    //R5RSCompletionItem item = new R5RSCompletionItem(keyword, keywordType, keywordSyntax, keywordDoc, firstOffset, lastOffset);
    
  }

  public BTree loadOrCreateBTree(RecordManager aRecordManager,
    String aName, Comparator aComparator)
    throws IOException
  {
    // So you can't remember the recordID of the B-Tree? Well, let's
    // try to remember it from its name...
    long recordID = aRecordManager.getNamedObject(aName);
    BTree tree = null;

    if (recordID == 0)
    {
      // Well, the B-Tree has not been previously stored,
      // so let's create one
      tree = BTree.createInstance(aRecordManager, aComparator);
      // store it with the given name
      aRecordManager.setNamedObject(aName, tree.getRecid());
      // And commit changes
      aRecordManager.commit();
    }
    else
      // Yes, we already created this B-Tree in a previous run,
      // so let's retrieve it from the record manager
      tree = BTree.load(aRecordManager, recordID);
    return tree;
  }

  private RecordManager getDatabase()
  {
    if (recordManager == null)
    {
      
      
       URL pluginInternalURL = SchemeScriptPlugin.getDefault().getBundle().getEntry("r5rs-completion.db"); 
       
      
      String pluginFilePath;
	  try {
		pluginFilePath = FileLocator.resolve(pluginInternalURL).getFile();
	  }
	  catch (IOException e) {
		  return null;
	  }
      File file = new File(pluginFilePath);
      
      if (file == null)
        Logger.getLogger(R5RSCompletionDatabase.class.getName()).severe("Cannot find file");
      else
      {
        int i = file.getAbsolutePath().lastIndexOf(".db");
        
        String fileName = file.getAbsolutePath().substring(0, i);

        try
        {
          recordManager = RecordManagerFactory.createRecordManager(fileName);
          index = loadOrCreateBTree(recordManager, "KEYWORDS", new StringComparator());
          String allKeywordsAsOne = (String) index.find("KEYWORDS");
          String[] allKeywords = allKeywordsAsOne.split(" ");
          keywords = new TreeSet<String>();
          for (String keyword : allKeywords)
            keywords.add(keyword.trim());
        }
        catch (Throwable ex)
        {
          System.out.println(ex.getMessage());
        }
        Logger.getLogger(R5RSCompletionDatabase.class.getName()).fine("File is " +
          fileName);
      }
    }
    return recordManager;
  }
 public static void main(String[] args) {

	System.out.println(R5RSCompletionDatabase.getInstance().getItem("map")); 	
	
	
 }
}
